package com.example.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

@SpringBootApplication
public class ZookeeperApplication {

    public static void main(String[] args) throws Exception {
//        SpringApplication.run(ZookeeperApplication.class, args);

        // zk 有session概念  没有线程池概念
        // watch 观察 回调
        // new zk 传入的watch 是session级别的 和path  node 没有关系
        // watch的回调方法
        /**
         * 没有引入 CountDownLatch 之前 启动zookeeper是 ing 状态
         *  引入之后 会变成 end状态
         */
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("localhost:2181", 3000, watchedEvent -> {
            // 获取状态
            Watcher.Event.KeeperState state = watchedEvent.getState();
            // 获取类型
            Watcher.Event.EventType type = watchedEvent.getType();
            System.out.println("new zk event:"+watchedEvent.toString());


            switch (state) {
                case Unknown:
                    break;
                case Disconnected:
                    break;
                case NoSyncConnected:
                    break;
                case SyncConnected:
                    System.out.println("connect success");
                    countDownLatch.countDown();
                    break;
                case AuthFailed:
                    break;
                case ConnectedReadOnly:
                    break;
                case SaslAuthenticated:
                    break;
                case Expired:
                    break;
            }

            switch (type) {
                case None:
                    break;
                case NodeCreated:
                    break;
                case NodeDeleted:
                    break;
                case NodeDataChanged:
                    break;
                case NodeChildrenChanged:
                    break;
            }

        });


        countDownLatch.await();
        ZooKeeper.States state = zooKeeper.getState();
        switch (state) {
            case CONNECTING:
                System.out.println("ing.....");
                break;
            case ASSOCIATING:
                break;
            case CONNECTED:
                System.out.println("end.....");
                break;
            case CONNECTEDREADONLY:
                break;
            case CLOSED:
                break;
            case AUTH_FAILED:
                break;
            case NOT_CONNECTED:
                break;
        }

        /**
         * 创建节点
         * 两种方式
         *  同步创建
         *      参数：path:路径  data：数据  id  createMode:节点类型
         *  异步创建
         *      参数：path:路径  data：数据  id  createMode:节点类型
         */
        // 同步创建
        String s = zooKeeper.create("/mytest", "我的数据".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        // 异步创建
//        zooKeeper.create("/mytest", "异步创建信息".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {
//            @Override
//            public void processResult(int i, String s, Object o, String s1) {
//                System.out.println("sssss");
//            }
//        },new Object());

        // 获取节点信息
        Stat stat1 = new Stat();
        byte[] data = zooKeeper.getData("/mytest", new Watcher() {
            // watcher 发生在 get exist 操作中
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("getData watcher: "+watchedEvent.toString());
                // 注册watcher【即 在注册一遍】
                // 为 true 是new zk 时的watcher
                try {
                    zooKeeper.getData("/mytest",this,stat1);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, stat1);
        System.out.println(new String(data));

        // 触发回调 数据修改 会触发data中watcher
        Stat stat = zooKeeper.setData("/mytest", "我的数据".getBytes(), 0);
        // 在修改一次 不会触发 【如果需要一直监测，需要在getData时继续注册这个watcher】
        Stat mytest = zooKeeper.setData("/mytest", "new Data".getBytes(), stat.getVersion());


        /**
         * 异步获取信息
         */
        System.out.println("-------async getData start----------");
        zooKeeper.getData("/mytest", false, new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int i, String s, Object o, byte[] bytes, Stat stat) {
                System.out.println("-------async getData callback----------");
                System.out.println(o.toString());
                System.out.println(bytes.toString());
            }
        },"xxxxx");
        System.out.println("-------async getData end----------");
    }

}
